package com.zsc.oj.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.oj.annotation.AuthCheck;
import com.zsc.oj.common.BaseResponse;
import com.zsc.oj.common.DeleteRequest;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.common.ResultUtils;
import com.zsc.oj.constant.FileConstant;
import com.zsc.oj.constant.RedisConstant;
import com.zsc.oj.constant.UserConstant;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.exception.ThrowUtils;
import com.zsc.oj.manager.CosManager;
import com.zsc.oj.mapper.AcceptQuestionMapper;
import com.zsc.oj.model.dto.file.UploadFileRequest;
import com.zsc.oj.model.dto.user.*;
import com.zsc.oj.model.entity.User;
import com.zsc.oj.model.enums.FileUploadBizEnum;
import com.zsc.oj.model.enums.UserRoleEnum;
import com.zsc.oj.model.vo.AcceptQuestionVO;
import com.zsc.oj.model.vo.LoginUserVO;
import com.zsc.oj.model.vo.UserVO;
import com.zsc.oj.service.AcceptQuestionService;
import com.zsc.oj.service.UserService;
import com.zsc.oj.service.impl.UserServiceImpl;
import com.zsc.oj.utils.UploadFileUtils;
import com.zsc.oj.utils.ValidFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBitSet;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends UploadFileUtils<User,UserService>{

    @Resource
    private UserService userService;

    @Resource
    private AcceptQuestionService acceptQuestionService;

    @Resource
    private AcceptQuestionMapper acceptQuestionMapper;



    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }


    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((UserServiceImpl.SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);

        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVO(userPage.getRecords());
        //过滤掉当前登录用户
        List<UserVO> newUserVOList = userVOList.stream().filter(uservo -> !uservo.getId().equals(loginUser.getId())).collect(Collectors.toList());
        userVOPage.setRecords(newUserVOList);
        return ResultUtils.success(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
            HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 设置用户为管理员
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/set/admin/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> setAdmin(@PathVariable Long id,HttpServletRequest request){
        User user = userService.getById(id);
        UpdateWrapper<User> updateWrapper = new UpdateWrapper();
        if(user.getUserRole() == UserConstant.DEFAULT_ROLE){
            updateWrapper.eq("id",id);
            updateWrapper.set("userRole",UserConstant.ADMIN_ROLE);
            boolean result = userService.update(updateWrapper);
            return ResultUtils.success(result);
        }
        else{
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户已是管理员");
        }
    }

    /**
     * 排行榜
     * @return
     */
    @GetMapping("/get/rank")
    public BaseResponse<List<AcceptQuestionVO>> getRank(){
        List<AcceptQuestionVO> acceptQuestionVOList = acceptQuestionMapper.listRank();
        List<AcceptQuestionVO> newAcceptQuestionVOList = new ArrayList<>();
        for (AcceptQuestionVO acceptQuestionVO : acceptQuestionVOList) {
            Long userId = acceptQuestionVO.getUserId();
            User user = userService.getById(userId);
            acceptQuestionVO.setUser(user);
            newAcceptQuestionVOList.add(acceptQuestionVO);
        }
        return ResultUtils.success(newAcceptQuestionVOList);
    }

    /**
     * 判断是否是我的好友
     * @param fromId
     * @param request
     * @return
     */
    @PostMapping("/is/friend/{fromId}")
    public BaseResponse<Boolean> IsMyFriend(@PathVariable Long fromId,HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if(fromId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.isMyFriend(fromId,loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 展示我的好友
     * @param request
     * @return
     */
    @GetMapping("/show/friends")
    public BaseResponse<List<UserVO>> ShowMyFriends(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        List<UserVO> userVOList = userService.showMyFriends(loginUser);
        return ResultUtils.success(userVOList);
    }

    /**
     * 用户签到
     * @param request
     * @return
     */
    @PostMapping("/signin")
    public BaseResponse<Boolean> userSignIn(HttpServletRequest request){
        boolean isSignIn = userService.userSignIn(request);
        return ResultUtils.success(isSignIn);
    }

    /**
     * 获取签到记录
     * @param request
     * @return
     */
    @GetMapping("/get/signin")
    public BaseResponse<List<Integer>>selectSignInRecord(HttpServletRequest request){
        List<Integer> recordList = userService.selectSignInRecord(request);
        return ResultUtils.success(recordList);
    }

    /**
     * 封号处理
     * @param id
     * @return
     */
    @PostMapping("/band")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> bandUser(@RequestBody Long id){
        if(id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        String userRole = user.getUserRole();
        if(userRole.equals(UserRoleEnum.BAN.getValue())){
            user.setUserRole(UserRoleEnum.USER.getValue());
            boolean result = userService.updateById(user);
            return ResultUtils.success(result);
        }
        if(userRole.equals(UserRoleEnum.ADMIN.getValue()) ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不能封管理员账号");
        }
        if(userRole.equals(UserRoleEnum.USER.getValue())){
            user.setUserRole(UserRoleEnum.BAN.getValue());
            boolean result = userService.updateById(user);
            return ResultUtils.success(result);
        }
        return ResultUtils.success(true);
    }

    /**
     * 用户上传头像
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<Boolean> uploadUserAvatar(@RequestPart("file") MultipartFile multipartFile,
                                                  UploadFileRequest uploadFileRequest, HttpServletRequest request){
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 检验文件大小
        ValidFileUtils.validFile(multipartFile, fileUploadBizEnum);

        User loginUser = userService.getLoginUser(request);

        //文件上传
//        boolean result = userService.uploadUserAvatar(fileUploadBizEnum,multipartFile,loginUser);
        boolean result = super.upload(fileUploadBizEnum, multipartFile, loginUser);

        return ResultUtils.success(result);
    }
}
